<?php
 /**
  * Main file
 *  @package shakephp
 *  @subpackage core
 */

require_once("framework/config.inc.php");
require_once("framework/autoload.inc.php");

 /**
 * Dispatch function
 * 
 * Creates a controller object and call for some of its methods.
 * The default method is Config::$DEFAULT_METHOD . If the request contains
 * $_GET[Config::$METHOD_CHOOSER], then the value of this variable will be
 * the name of the controller's method to be called.
 *  @see Config 
 * @param string $controller_name [optional] Name of the controller's class
 *  Parameter that informs the name of the controller class. This name should
 *  be present in the array Config::$CONTROLLERS
 *  By default the dispatch function will try to find a class with the name
 *  $controller_name."_controller"
 */
function dispatch($controller_name = null) {
	//Try to get the controller's name, if not passed as argument
	if($controller_name==null) {
		$file = explode(".", basename($_SERVER["SCRIPT_NAME"]));
		$controller_name = $file[0]."_controller";
	}

	//Creates the controller or returns "Fatal Error"
	$controller = new $controller_name($_GET, $_POST);

	//Discovering which method must be called
	if( isset($_GET[Config::$METHOD_CHOOSER]) && 
	  !empty($_GET[Config::$METHOD_CHOOSER]))
		$acao = $_GET[Config::$METHOD_CHOOSER];
	else
		$acao = Config::$DEFAULT_METHOD;
		
	//Trying to call the method
	if(!method_exists($controller,$acao))
		throw new Exception("Action $acao not found.");
	else
		if(is_callable(array($controller, $acao)))
			$controller->$acao();
		else
			throw new Exception("Action $acao not found.");
}

?>
